package com.markerhub.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.Blog;
import com.markerhub.service.BlogService;
import com.markerhub.service.UserService;
import com.markerhub.util.ShiroUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;


/**
 * <p>
 *  前端控制器
 * </p>
 * 1.分页接口
 * 2.详情接口{id}占位符
 * 3.保存接口
 *
 * queryWrapper是条件构造器
 * 可以进一步封装
 *
 * @author springboot vue
 * @since 2021-03-01
 */
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;
    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){
        ///创建page
        Page page=new Page(currentPage,3);
        //传入page，传入查询的Bloglist并按创建时间降序排序
        IPage pageData= blogService.page(page,new QueryWrapper<Blog>().orderByDesc("created"));
        return Result.success(pageData);
    }
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id")Long id){
        Blog blog = blogService.getById(id);
        System.out.println(blog);
        if(blog==null){
            return Result.fail("数据为空");
        }
        return Result.success(blog);
    }

    /**
     * 编辑博客
     * 判断字段合法性
     * 只能编辑自己的文章，判断Id
     *
     * @param blog
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog){
        Blog temp;
        if(blog.getId()!=null){
            temp=blogService.getById(blog.getId());
            if(!temp.getUserId().equals(ShiroUtils.getProfile().getId())){
                return Result.fail("没有权限编辑");
            }
        }else {
            temp = new Blog();
            temp.setUserId(ShiroUtils.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }
        //把传进的blog内容复制给temp然后插入数据库或者更新 blog->temp 忽略一些字段
        //也可以直接用set方法，比较麻烦
        BeanUtil.copyProperties(blog,temp,"id","userId","created","status");
        blogService.saveOrUpdate(temp);

        return Result.success(null);
    }

}
